﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BrnMall.Manager.Domain.User;
using PetaPoco;

namespace BrnMall.Manager.Manager.User
{
    public static class UserCashManager
    {

        /// <summary>
        /// 添加会员余额记录
        /// </summary>
        /// <param name="model"></param>
        public static void Add(UserCash model)
        {
            using (var db = new QDMallDatabase())
            {
                db.Insert(model);
            }
        }


        /// <summary>
        /// 返回用余额
        /// </summary>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public static UserCash GetInfo(int uid)
        {
            try
            {
                using (var db = new QDMallDatabase())
                {
                    return db.SingleOrDefault<UserCash>("select top 1 * from cash_UserCash where uid=@0", uid);
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
        }

        /// <summary>
        /// 更新余额
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="cash">余额</param>
        /// <param name="giveCash">赠送总金额(从开通到现在为止的赠送总金额)</param>
        /// <returns></returns>
        public static int UpdateCash(int uid, string cash, decimal giveCash)
        {
            try
            {
                using (var db = new QDMallDatabase())
                {
                    return db.Execute("update cash_UserCash set cash=@0,giveCash=@1 where uid=@2", cash, giveCash, uid);
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
        }

        public static Page<UserCash> GetListPage(int storeId, string nickName, int page, int pageSize = 15, string orderBy = "")
        {
            var sql = new StringBuilder();
            sql.AppendFormat("select * from cash_usercash where storeId={0} ", storeId);

            //昵称查询
            if (!string.IsNullOrEmpty(nickName))
            {
                var uid = UsersManager.GetIdsByNickNameToString(nickName, 20);
                if (uid.IndexOf(",") > -1)
                    sql.AppendFormat(" and uid in({0})", uid);
                else
                    sql.AppendFormat(" and uid={0}", uid);

            }

            //排序
            if (orderBy.Equals("top"))
                sql.Append(" order by cash_decode desc");

            using (var db = new QDMallDatabase())
            {
                return db.Page<UserCash>(page, pageSize, sql.ToString());
            }
        }
    }
}
